<template>
  <div class="home">
    <span
      v-if="roleIdList.length > 1 && !isSearchGlobalShow"
      @click="selRole = true"
      class="role-change"
      >切换角色</span
    >
    <div @click="selRole = false" :class="{ mask: selRole }"></div>

    <div v-if="isSearchGlobalShow">
      <h-search
        @close-search="
          () => {
            isSearchGlobalShow = false;
            $bus.$emit('isShowNavigation', isSearchGlobalShow);
          }
        "
      />
    </div>
    <div v-show="!isSearchGlobalShow">
      <a-spin :spinning="loginLoading" :tip="freeLoginTip">
        <div class="home-head">
          <div class="user-info">
            <user-info
              :avatar="avatar"
              :userName="userName"
              :weather="weatherInfo"
            />
          </div>
          <show-msg :msg-data="headMessage" @message-click="messageClick" />
        </div>
        <!-- flowLoading -->
        <a-spin :spinning="flowLoading" tip="载入中...">
          <flow-layout
            @click="flowLayoutClick"
            :layoutList="flowList"
            :count="count"
            class="flow-layout"
            ref="flowlayout"
          >
            <div slot="search" v-show="!flowLoading">
              <img
                @click="
                  () => {
                    isSearchGlobalShow = true;
                    $bus.$emit('isShowNavigation', isSearchGlobalShow);
                  }
                "
                class="home-search-icon"
                src="~@/assets/img/search.png"
                alt="搜索"
              />
            </div>
          </flow-layout>
        </a-spin>
      </a-spin>
    </div>
    <action-drawer
      title="角色选择"
      :visible="selRole"
      :headerStyle="{
        'border-bottom': '1px solid #e3e6ec',
      }"
      :bodyStyle="{
        padding: 0,
        'box-shadow': 'none',
      }"
      @close="selRole = false"
    >
      <div slot="content">
        <a-list item-layout="horizontal" :data-source="roleIdList">
          <a-list-item
            @click="changeRole(item)"
            slot="renderItem"
            slot-scope="item, index"
          >
            <a-list-item-meta>
              <div slot="title">
                <div
                  :class="{
                    'home-role-item': true,
                    'home-role-item-last': index === roleIdList.length - 1,
                  }"
                >
                  <span
                    >{{ item.name }}
                    <span v-show="roleNow === item.name">(当前角色)</span>
                  </span>
                </div>
              </div>
            </a-list-item-meta>
          </a-list-item>
        </a-list>
        <div @click="selRole = false" class="home-role-item home-role-cancel">
          取消
        </div>
        <div class="zzz"></div>
      </div>
    </action-drawer>
  </div>
</template>

<script>
/*eslint-disable*/
import { getJW, getWeather } from "@/api/weather";
import { getCount, getCogetCurrentUserTodoCountunt } from "@/api/home";
import UserInfo from "./home/home-userinfo/index.vue";
import ShowMsg from "./home/home-showmsg/index.vue";
import { id, SHOW_ALL } from "./home/jsondata";
import { toLogin } from "@/utils/login.js";
import { messageType } from "@/api/message";
import freeLogin from "@/utils/freelogin.js";



export default {
  /* data */
  data() {
    return {
      selRole: false,
      roleNow: "",
      roleIdList: [],
      avatar: "",
      isSearchGlobalShow: false,
      flowLoading: false,
      userName: "",
      weatherInfo: {},
      headMessage: [
        { name: "待办数", total: 0 },
        { name: "已办数", total: 0 },
        { name: "暂存记录", total: 0 },
      ],
      flowList: [
        {
          title: "我的待办",
          children: [],
        },
        {
          title: "业务中心",
          children: [
            {
              title: "我的申请",
              count: 0,
              name:'我的申请',
              // eslint-disable-next-line global-require
              imgImport: require("@/assets/img/flow/wdsq.png"),
              [id]: "1-0",
            },
            {
              title: "已办申请",
              count: 0,
              name:'已办申请',
              // eslint-disable-next-line global-require
              imgImport: require("@/assets/img/flow/ybsq.png"),
              [id]: "1-1",
            },
            {
              title: "抄送",
              count: 0,
              name:'抄送',
              // eslint-disable-next-line global-require
              imgImport: require("@/assets/img/flow/cs.png"),
              [id]: "1-2",
            },
          ],
        },
      ],
      daiBanMap: {},
      count: 0
    };
  },
  mixins: [freeLogin],
  /* data */
  methods: {
    changeRole(item) {
      localStorage.setItem("roleNow", item.name);
      location.reload();
    },
    messageClick(item) {
      const { name } = item;
      if (name === "已办数") {
        sessionStorage.setItem("homeItemClick", "1-1");
        this.$router.push("/itemContent");
      }
    },
    flowLayoutClick(k) {
      sessionStorage.setItem("flowLayoutName", k.name);
      const item = k[id];
      let showSPBtns = "1"; //是否显示通过驳回等按钮
      if (item) {
        showSPBtns = "0";
        sessionStorage.setItem("showSPBtns", showSPBtns);
        sessionStorage.setItem("homeItemClick", item);
        this.$router.push("/itemContent");
        return;
      }
      sessionStorage.setItem("showSPBtns", showSPBtns);
      if (k.count === 0) {
        return this.$message.warning(`${k.title}暂无待办内容`);
      }
      if (this.daiBanMap[k.id] !== undefined) {
        const { id } = k;
        if (id) {
          sessionStorage.setItem("homeItemClick", id);
          this.$router.push("/itemContent");
        }
      }
    },

    getGaoGeApiSuccess(res) {
      if (res.status === 200) {
        if (res.data.infocode === "10000") {
          return true;
        }
      }
      return false;
    },
    changeLastFlowLayoutHeight() {
      if (this.flowList.length === 0) {
        return;
      }
      const ele = this.$refs.flowlayout;
      if (ele) {
        const eleChildren = ele.$children;
        if (eleChildren) {
          if (eleChildren.length) {
            const flowEle = this.$refs.flowlayout.$children[
              this.flowList.length - 1
            ].$el;
            const clientH = document.documentElement.clientHeight;
            const eleH = flowEle.offsetTop + flowEle.offsetHeight;
            if (eleH < clientH) {
              flowEle.style.height = `${clientH / 2 - flowEle.offsetTop}px`;
            }
          }
        }
      }
    },
    // 获取天气
    getTemper() {
      getJW().then((res) => {
        if (this.getGaoGeApiSuccess(res)) {
          getWeather(res.data.adcode).then((res1) => {
            if (this.getGaoGeApiSuccess(res1)) {
              if (res1.data.lives.length > 0) {
                this.weatherInfo = res1.data.lives[0];
              }
            }
          });
        }
      });
    },

    getHeadMessage() {
      const userId = localStorage.getItem("userId");
      if (!userId) {
        return;
      }
      getCount({
        userId,
      }).then((res) => {
        if (res.code === 200 && res.success) {
          res.data.shift();
          const arr = ["待办数", "已办数", "暂存记录"];
          res.data.forEach((item, index) => {
            // eslint-disable-next-line no-param-reassign
            item.name = arr[index];
          });
          this.headMessage = res.data;
        }
      });
    },

    getDaibanItems() {
      this.flowLoading = true;
      getCogetCurrentUserTodoCountunt({}).then(
        (res) => {
          this.flowLoading = false;
          if (res.success && res.code === 200) {
            const picNameArr = ["yusuanju", "jjk", "zhk", "ybsq"];
            const picArr = [];
            picNameArr.forEach((item) => {
              const obj = {
                pic: require(`@/assets/img/flow/${item}.png`),
              };
              picArr.push(obj);
            });
            res.data.forEach((item, index) => {
              item.title = item.name;
              item.imgImport = picArr[index % 4].pic;
              this.daiBanMap = { 
                  ...this.daiBanMap,
                  ...{
                    [item.id]: item.title
                  }
                };
            });
            this.flowList[0].children = res.data;

            if (this.roleNow === "领导") {
              this.flowList[1].children.push(SHOW_ALL);
            }
            if (res.data.length === 1) {
              this.count = res.data[0].count
            } else {
              this.count = 0
            }
          }
        },
        (err) => {
          this.flowLoading = false;
        }
      );
    },
    async pageTextInit() {
      await toLogin(this);
      await this.pageInit();
    },
    async pageInit() {
      const {
        changeLastFlowLayoutHeight,
        getDaibanItems,
        getHeadMessage,
      } = this;
      const roleIdList = JSON.parse(localStorage.getItem("roleIdList"));
      const roleNow = localStorage.getItem("roleNow");
      roleIdList && (this.roleIdList = roleIdList);
      roleNow && (this.roleNow = roleNow);
      messageType({ userId: localStorage.getItem("userId") }).then((res) => {
        if (res.code && res.success) {
          this.$emit("messageReaded", res.data > 0);
        }
      });
      await getHeadMessage();
      await getDaibanItems();
      changeLastFlowLayoutHeight();
      const userName = localStorage.getItem("userName");
      const avatar = localStorage.getItem("avatar");
      if (avatar) {
        this.avatar = avatar;
      }
      if (userName) {
        this.userName = userName;
      }
    },
  },
  computed: {
    isBoss() {
      return this.roleNow === "领导";
    },
  },
  created() {
    sessionStorage.clear();
    const { getTemper } = this;
    getTemper();
  },
  components: {
    UserInfo,
    ShowMsg,
    HSearch: () => import("@/views/home/home-search"),
  },
  watch: {
    flowLoading: {
      handler: function(newV) {
        this.$emit("login-loading", newV);
      },
      immediate: true,
    },
  },
};
</script>
<style lang="less" scoped>
.mask {
  width: 100%;
  height: 100vh;
  position: absolute;
  z-index: 999;
  background-color: rgba(0, 0, 0, 0.45);
  transition: opacity 0.3s linear, height 0s ease 0.3s;
}
.home {
  width: 100%;
  height: 100vh;
  position: relative;
  .home-head {
    background: url("~@/assets/img/home-head-bg.png") no-repeat;
    background-size: 100%;
    height: 211px;
    // background-position: 0 -20px;
  }
  .user-info {
    &::before {
      content: "";
      display: block;
      height: 88px;
    }
  }
  .flow-layout {
    margin-top: 30px;
    border-bottom: 60px #fff solid;
  }
  .home-search-icon {
    width: 20px;
    height: 20px;
  }
}
/deep/ .ant-list-item {
  padding: 0;
}
.home-role-item {
  height: 100%;
  padding: 12px 0;
  text-align: center;

  font-size: 17px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #333333;
  background-color: #fff;
}
.home-role-cancel {
  border-radius: 3px;
  border-top: 8px solid rgba(0, 0, 0, 0.45);
}
/deep/ .ant-drawer-content {
  border-radius: 3px;
  box-shadow: none;
  background-color: rgba(0, 0, 0, 0);
}
.role-change {
  position: absolute;
  z-index: 9;
  padding: 12px;

  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  color: #ffffff;
}
.zzz {
  height: 12px;
  background-color: #888888;
}
/deep/ .ant-list-items {
  background-color: #fff;
}
</style>
